package io;


import org.junit.Test;

import java.io.*;

/**
 * @description:
 * @author: apple
 * @date:  2021/12/25 7:11 下午
 * @version 1.0
 **/
public class FileReaderWriterTest {

    @Test
    public void test1()  {
        File f = new File("test.txt");

        if (f.exists()) {
            FileReader reader = null;
            try {
                 reader = new FileReader(f);
                // 返回读入的一个字符，达成尾巴就是-1
                int i = -1;
                while ((i = reader.read())!= -1) {
                    System.out.println(i);
                }
            }catch (IOException ex) {
                ex.printStackTrace();
            }finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }

        }
    }

    @Test
    public void test2()  {
        File f = new File("test.txt");
        FileReader reader = null;
        try {
            reader = new FileReader(f);
            char[] cbuf = new char[5];
            int len;
            while ((len = reader.read(cbuf)) != -1) {
                for (int i = 0; i < len; i++) {
                    System.out.print(cbuf[i]);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }



    }


    @Test
    public void test3() throws IOException {
        // 如果文件不存在，则自动生成
        // 如果不存在，可以重新覆盖，也可以追加
        File f = new File("test1.txt");
        FileWriter writer = new FileWriter(f , true);
        writer.write("hello".toCharArray());
        writer.close();
    }
}
